package com.meij.activity.user;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.anno.ActionBarSet;
import com.anno.ActionBarSet.WAY;
import com.meij.MJApplaction;
import com.meij.R;
import com.meij.activity.MjActivity;
import com.meij.bean.Person;
import com.meij.http.Json;
import com.meij.http.MJNetCallBack;
import com.meij.http.Url;
import com.meij.util.Info;

@ActionBarSet(title = "登录", way = WAY.TITLE, homeAsUpEnabled = true)
public class LoginActivity extends MjActivity {
	// 登录信息相关
	private String phone, pass;
	// 控件
	private EditText edite1, edite2;
	// 摇晃提示动画
	private Animation shake;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		initView();
	}

	/***
	 * 初始化UI
	 */
	private void initView() {
		shake = AnimationUtils.loadAnimation(this, R.anim.shake);
		edite1 = (EditText) findViewById(R.id.editText1);
		edite2 = (EditText) findViewById(R.id.editText2);
		edite2.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				switch (actionId) {
				case EditorInfo.IME_ACTION_DONE:
					submit(null);
					break;
				}
				return false;
			}
		});
	}

	/***
	 * 信息校验
	 */
	private boolean checkInfo() {
		phone = edite1.getText().toString();
		if (TextUtils.isEmpty(phone)) {
			Toast(R.string.sign_numhit);
			edite1.requestFocus();
			edite1.startAnimation(shake);
			return false;
		}
		pass = edite2.getText().toString();
		if (TextUtils.isEmpty(pass)) {
			Toast(R.string.sign_passhit);
			edite2.requestFocus();
			edite2.startAnimation(shake);
			return false;
		}
		return true;
	}

	public void findPwd(View view) {
		Intent intent = new Intent(this, FindPwdActivity.class);
		startActivity(intent);
	}

	public void submit(View view) {
		if (checkInfo()) {
			String url = Url.login + "?mobile=" + phone + "&pwds=" + pass + "&lat=" + latitude + "&lng=" + longitude;
			MJNetCallBack callBack = new MJNetCallBack(this) {
				@Override
				public void onSuccess(JSONObject object) {
					super.onSuccess(object);
					MJApplaction.userInfo = Json.getUserInfo(object);
					Person person = Json.getPerson(object);
					MJApplaction.userInfo.setPerson(person);
					Info.saveUserInfo(LoginActivity.this);
					Toast("登录成功");
					finish();
				}
			};
			getJson(url, callBack);
		}
	}
}
